package com.chuangke.file.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangke.admin.data.builder.UserDataBuilder;
import com.chuangke.admin.entity.SysUserDataDept;
import com.chuangke.admin.entity.SysUserRole;
import com.chuangke.admin.service.SysUserDataDeptService;
import com.chuangke.admin.service.SysUserRoleQueryService;
import com.chuangke.common.constant.CacheKeyConstants;
import com.chuangke.common.constant.Masks;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.DataBuilder;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.file.dao.SysFilePermissionMapper;
import com.chuangke.file.domain.PermissionSaveDTO;
import com.chuangke.file.model.SysFilePermission;
import com.chuangke.file.service.SysFilePermissionService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 文件权限管理Service业务层处理
 * 
 * @author chuangke
 * @date "2020-09-03"
 */
@Service
public class SysFilePermissionServiceImpl extends ServiceImpl<SysFilePermissionMapper, SysFilePermission>
		implements SysFilePermissionService {

	@Autowired
	private SysFilePermissionMapper sysFilePermissionMapper;
	@Autowired
	private SysUserDataDeptService sysUserDataDeptService;
	@Autowired
	private SysUserRoleQueryService sysUserRoleQueryService;

	@CacheEvict(cacheNames = CacheKeyConstants.FILE_PERMISSION,allEntries = true)
	public boolean save(SysFilePermission entity) {
		return super.save(entity);
	}

    /**
	 * 查询文件权限管理列表
	 * 
	 * @return 文件权限管理
	 */
	@Override
	@Cacheable(cacheNames = CacheKeyConstants.FILE_PERMISSION, key = "'list1-user:'+#userId+'-'+#authFileType")
	public List<SysFilePermission> list(String authFileType, String userId) {
		String isAuthFile = null ;
		if(SysFilePermission.AUTH_FILE_TYPE_FILE.equals(authFileType)) {
			isAuthFile = Masks.BOOL_YES ;
		}else if(SysFilePermission.AUTH_FILE_TYPE_DBANK.equals(authFileType)) {
			isAuthFile = Masks.BOOL_NO ;
		}
		
		List<SysUserDataDept> userDeptList = sysUserDataDeptService.find(userId) ;
		userDeptList = userDeptList==null ? new ArrayList<>() : userDeptList ;
		List<String> deptList = userDeptList.stream().map(SysUserDataDept::getDeptId)
				.collect(Collectors.toList());
		
		List<SysUserRole> userRoleList = sysUserRoleQueryService.findByUserId(userId) ;
		userRoleList = userRoleList==null ? new ArrayList<>() : userRoleList ;
		List<String> roleList = userRoleList.stream().map(SysUserRole::getRoleId)
				.collect(Collectors.toList());

		List<SysFilePermission> resultList = sysFilePermissionMapper.selectAuthDbank(isAuthFile, userId, deptList,
				roleList);

		DataBuilder.of(resultList).appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdBy"),
				new DataBuildConfig("updatedBy", "updatedBy")).build();
		return resultList;
	}

	@Cacheable(cacheNames = CacheKeyConstants.FILE_PERMISSION, key = "'list2-user:'+#userId+'-dbank:'+#dbankId")
	public List<SysFilePermission> listAuthFiles(String dbankId, String userId) {
		List<String> deptList = sysUserDataDeptService.find(userId).stream().map(SysUserDataDept::getDeptId)
				.collect(Collectors.toList());
		List<String> roleList = sysUserRoleQueryService.findByUserId(userId).stream().map(SysUserRole::getRoleId)
				.collect(Collectors.toList());

        return sysFilePermissionMapper.selectAuthFiles(dbankId, userId, deptList,
				roleList);
	}

	/**
	 * 新增文件权限管理
	 * 
	 * @return 结果
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = CacheKeyConstants.FILE_PERMISSION,allEntries = true)
	public void savePermission(PermissionSaveDTO psDto) {
		if (CollectionUtils.isEmpty(psDto.getFiles())) {
			return;
		}

		this.remove(new QueryWrapper<SysFilePermission>().lambda().in(SysFilePermission::getFileId, psDto.getFiles()));

		if (CollectionUtils.isEmpty(psDto.getPermissions())) {
			return;
		}

		psDto.getPermissions().forEach(permission -> {
			if (StrUtil.isBlank(permission.getId())) {
				permission.setId(IdManager.nextId());
			}
			if (!StrUtil.isBlank(permission.getFileId())) {
				permission.setIsAuthFile(Masks.BOOL_YES);
			} else {
				permission.setIsAuthFile(Masks.BOOL_NO);
			}
		});
		this.saveBatch(psDto.getPermissions());
	}

	/**
	 * 批量删除文件权限管理
	 * 
	 * @param ids 需要删除的文件权限管理ID
	 * @return 结果
	 */
	@Override
	@CacheEvict(cacheNames = CacheKeyConstants.FILE_PERMISSION,allEntries = true)
	public int delete(List<String> ids) {
		return sysFilePermissionMapper.deleteBatchIds(ids);
	}

	@Override
	@Cacheable(cacheNames = CacheKeyConstants.FILE_PERMISSION, key = "'list3-'+#fileId")
	public Map<String, List<SysFilePermission>> listFilePermission(String fileId) {
		List<SysFilePermission> list = sysFilePermissionMapper
				.selectList(new QueryWrapper<SysFilePermission>().lambda().eq(SysFilePermission::getFileId, fileId));
		return list.stream().collect(Collectors.groupingBy(SysFilePermission::getAuthType));
	}

	@Override
	@CacheEvict(cacheNames = CacheKeyConstants.FILE_PERMISSION,allEntries = true)
	public void removeByFiles(List<String> fileIds) {
		this.remove(new QueryWrapper<SysFilePermission>().lambda().in(SysFilePermission::getFileId, fileIds));
	}

	@Override
	@CacheEvict(cacheNames = CacheKeyConstants.FILE_PERMISSION,allEntries = true)
	public void change() {
		//权限变更，只需要注销缓存，不做其他任何处理
	}

}
